package com.hsc.www;

import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class UserServicesImp implements UserServices {

    Map<Integer, User> db = new ConcurrentHashMap(); //模拟数据库

    @Override
    public int addUser(Integer id, String name) {
        System.out.println("sql-addUser");
        User user = new User();
        user.setId(id);
        user.setName(name);
        db.put(user.getId(), user);
        return user.getId();
    }

    @Override
    public User findByName(String name) {
        System.out.println("sql-findByName");
        return db.values().stream().filter(item -> item.getName().equals(name)).findAny().get();

    }

    @Override
    public User findById(int id) {
        System.out.println("sql-findById");
        return db.get(id);
    }


    @Override
    public User findByIdAndName(int id, String name) {
        System.out.println("sql-findByIdAndName");
        User user = db.get(id);
        if (user != null && user.getName().equals(name)) {
            return user;
        } else {
            return null;
        }
    }

    @Override
    public void updateById(int id, String name) {
        System.out.println("sql-updateById");
        User user = db.get(id);
        if (user != null) {
            user.setName(name);
        }
    }

    @Override
    public void deleteById(int id) {
        System.out.println("sql-deleteById");
        db.remove(id);
    }

    @Override
    public List<User> findAll() {
        System.out.println("sql-findAll");
        return new ArrayList<>(db.values());
    }
}